package com.kfh.ybracelet.base;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kfh.ybracelet.R;
import com.kfh.ybracelet.audio.MediaRecordManager;
import com.kfh.ybracelet.db.DatabaseManager;
import com.kfh.ybracelet.fragment.ChatFragment;
import com.kfh.ybracelet.fragment.FindFragment;
import com.kfh.ybracelet.fragment.LocationFragment;
import com.kfh.ybracelet.fragment.MyFragement;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;
import com.umeng.update.UmengUpdateAgent;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import de.greenrobot.event.EventBus;

/**
 * 首页
 * Created by Administrator on 2015/7/14.
 */
public class HomeActivity extends BaseActivity {

    /**
     * fragment 管理者
     */
    private FragmentManager manager;
    private FindFragment findFragment;
    private LocationFragment locationFragment;
    private ChatFragment chatFragment;
    private MyFragement myFragement;

    private TextView tv_location;
    private TextView tv_chat;
    private TextView tv_find;
    private TextView tv_my;

    private ImageView iv_location;
    private ImageView iv_chat;
    private ImageView iv_find;
    private ImageView iv_my;
    private TextView tv_msg_count;//未读消息个数
//    private ProgressDialog chatShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);

        //开启服务,登录mqtt
        mApplication.loginMqtt();

        initWidget();

        initFragment();

//        //设置极光推送的tag
        setAlias(sp.getString(Constant.USERID, ""));

////        友盟检查更新
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);
//        UpdateConfig.setDebug(true);//debug模式,发布时删除

        EventBus.getDefault().register(this);

    }

    /**
     * 更新小红点
     *
     * @param msb
     */
    public void onEventMainThread(String msb) {

        if (Constant.UPDATE_RED_COUNT.equals(msb))
            setRedCount();

    }

    @Override
    protected void onResume() {
        super.onResume();

//        LogUtil.e("tag", getClass().getName() + "   onresume  ");

        setRedCount();

        //只是为了提前获取录音权限用
        try {
            MediaRecordManager.getInstance().startRecordAndFile(this);
            MediaRecordManager.getInstance().stopRecordAndFile();
            MediaRecordManager.getInstance().deleteMediaRecord();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if (intent != null) {

//            boolean chooseLocation = intent.getBooleanExtra("chooseLocation", false);

            if (intent.getBooleanExtra("chooseLocation", false)) {

                //把所有的图标都变灰
                setSelectFalse();

                iv_location.setSelected(true);
                tv_location.setTextColor(getResources().getColor(R.color.red));

                chooseFragment(0);
            }

        }

    }

    // 设置红点个数
    public void setRedCount() {

        int sum = DatabaseManager.getInstance().queryAllUnReadCount(this, sp.getString(Constant.USERID, ""));

        if (sum == -100)
            return;

        if (sum > 99) sum = 99;
        tv_msg_count.setText(sum + "");
        tv_msg_count.setVisibility(sum > 0 ? View.VISIBLE : View.INVISIBLE);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);

    }

    private void initWidget() {

        RelativeLayout rl_location = (RelativeLayout) findViewById(R.id.rl_location);
        RelativeLayout rl_chat = (RelativeLayout) findViewById(R.id.rl_chat);
        RelativeLayout rl_find = (RelativeLayout) findViewById(R.id.rl_find);
        RelativeLayout rl_my = (RelativeLayout) findViewById(R.id.rl_my);

        iv_location = (ImageView) findViewById(R.id.iv_location);
        iv_chat = (ImageView) findViewById(R.id.iv_chat);
        iv_find = (ImageView) findViewById(R.id.iv_find);
        iv_my = (ImageView) findViewById(R.id.iv_my);

        tv_location = (TextView) findViewById(R.id.tv_location);
        tv_chat = (TextView) findViewById(R.id.tv_chat);
        tv_find = (TextView) findViewById(R.id.tv_find);
        tv_my = (TextView) findViewById(R.id.tv_my);

        tv_msg_count = (TextView) findViewById(R.id.tv_msg_count);

        rl_location.setOnClickListener(this);
        rl_chat.setOnClickListener(this);
        rl_find.setOnClickListener(this);
        rl_my.setOnClickListener(this);

    }

    /**
     * 初始化fragment
     */
    private void initFragment() {

        manager = getFragmentManager();

        iv_location.setSelected(true);
        tv_location.setTextColor(getResources().getColor(R.color.red));

        chooseFragment(0);
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.rl_location:

                //把所有的图标都变灰
                setSelectFalse();

                chooseFragment(0);

                //改变字体颜色和图片
                iv_location.setSelected(true);
                tv_location.setTextColor(getResources().getColor(R.color.red));
                break;

            case R.id.rl_chat:

                //把所有的图标都变灰
                setSelectFalse();

                chooseFragment(1);

                iv_chat.setSelected(true);
                tv_chat.setTextColor(getResources().getColor(R.color.red));

                break;
            case R.id.rl_find:

                //把所有的图标都变灰
                setSelectFalse();

                chooseFragment(2);

                iv_find.setSelected(true);
                tv_find.setTextColor(getResources().getColor(R.color.red));
                break;
            case R.id.rl_my:

                //把所有的图标都变灰
                setSelectFalse();
                //我的
                chooseFragment(3);

                iv_my.setSelected(true);
                tv_my.setTextColor(getResources().getColor(R.color.red));

                break;

        }
    }

    /**
     * 选择对应的fragment
     *
     * @param index 对应的fragment的角标
     */
    private void chooseFragment(int index) {

        FragmentTransaction transaction = null;
        if (manager != null) {
            transaction = manager.beginTransaction();
        }
        // 先移除掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
//        removeFragments(transaction);

        if (transaction == null)
            return;

        switch (index) {

            case 0: //定位

                if (locationFragment == null)
                    locationFragment = new LocationFragment();

                if (!locationFragment.isAdded()) {
                    transaction.replace(R.id.fl_base, locationFragment, Constant.CHILD);
                } else {
                    locationFragment.reBottonLocation();
                }

                break;

            case 1: //聊天

                if (chatFragment == null)
                    chatFragment = new ChatFragment();
                if (!chatFragment.isAdded()) {
                    transaction.replace(R.id.fl_base, chatFragment, Constant.NEWS);
                }

                break;

            case 2://发现

                if (findFragment == null)
                    findFragment = new FindFragment();
                if (!findFragment.isAdded()) {
                    transaction.replace(R.id.fl_base, findFragment, Constant.BABYTREE);
                }

                break;
            case 3: //我的

                if (myFragement == null)
                    myFragement = new MyFragement();
                if (!myFragement.isAdded()) {
                    transaction.replace(R.id.fl_base, myFragement, Constant.MY);
                }

                break;

        }

//            transaction.commit();
        transaction.commitAllowingStateLoss();

    }

//    /**
//     * 移除fragment
//     *
//     * @param transaction
//     */
//    private void removeFragments(FragmentTransaction transaction) {
//        if (transaction == null)
//            return;
//
//        if (homeFragment != null) {
//            transaction.remove(homeFragment);
//        }
//        if (locationFragment != null) {
//            transaction.remove(locationFragment);
//        }
//        if (chatFragment != null) {
//            transaction.remove(chatFragment);
//        }
//        if (myFragement != null) {
//            transaction.remove(myFragement);
//        }
//
//    }

    /**
     * 把所有的图标都变灰
     * 字体还原
     */
    private void setSelectFalse() {

        iv_location.setSelected(false);
        iv_chat.setSelected(false);
//        iv_photo.setSelected(false);
        iv_find.setSelected(false);
        iv_my.setSelected(false);

        tv_chat.setTextColor(getResources().getColor(R.color.text_color));
        tv_location.setTextColor(getResources().getColor(R.color.text_color));
        tv_find.setTextColor(getResources().getColor(R.color.text_color));
        tv_my.setTextColor(getResources().getColor(R.color.text_color));

    }

    private long mPressedTime = 0;

    @Override
    public void onBackPressed() {

        long mNowTime = System.currentTimeMillis();//获取第一次按键时间

        if ((mNowTime - mPressedTime) > 2000) {//比较两次按键时间差

            showToast("再按一次退出程序");

            mPressedTime = mNowTime;

        } else {//退出程序

            finish();
            mApplication.exit();

        }
    }

    // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口，在任何方便的地方调用都可以。
    private void setAlias(String phone) {
//			SharedPreferences sp = getSharedPreferences(Constant.CONFIG, MODE_PRIVATE);
//			boolean isSetAlias = sp.getBoolean("isSetAlias", false);

        if (CommonUtils.isNull(phone)) {
            String logs = "phone is empty";
            LogUtil.e("TAG", logs);
            return;
        }
//			if (isSetAlias) {
//				LogUtil.e("TAG", "设置了isSetAlias");
//				return;
//			}
        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, phone));
    }

    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    LogUtil.e("TAG", "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    LogUtil.e("TAG", "Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtil.e("TAG", logs);
//					// 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
//					SharedPreferences sp = getSharedPreferences(Constant.CONFIG, MODE_PRIVATE);
//					Editor editor = sp.edit();
//					editor.putBoolean("isSetAlias", true);// 是否设置了标签
//					editor.commit();
//					showToast("设置别名成功");

                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtil.e("TAG", logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtil.e("TAG", logs);
            }

        }
    };

}
